package cn.edu.nju.software.listener;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.swing.tree.DefaultMutableTreeNode;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.show.CategoryShow;
import cn.edu.nju.software.bean.storage.Category;
import cn.edu.nju.software.service.intf.CategoryService;
import cn.edu.nju.software.util.Constants;

public class SessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		Map<Integer, CategoryShow> categoriesMap = new HashMap<Integer, CategoryShow>();
		List<CategoryShow> mainCategoriesShow;
		WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getSession().getServletContext());
		CategoryService categoryService = (CategoryService) applicationContext.getBean("categoryService");
		
		try {
			DefaultMutableTreeNode rootNode = categoryService.getAllCategories();
			@SuppressWarnings("unchecked")
			Enumeration<DefaultMutableTreeNode> enumeration = rootNode.breadthFirstEnumeration();
			while (enumeration.hasMoreElements()) {
				DefaultMutableTreeNode currentNode = enumeration.nextElement();
				Category category = (Category) currentNode.getUserObject();
				categoriesMap.put(category.getCategoryID(), new CategoryShow(category, categoriesMap.get(category.getFatherID())));
			}
			
			int childCount = rootNode.getChildCount();
			CategoryShow rootCategory = new CategoryShow((Category) rootNode.getUserObject(), null);
			mainCategoriesShow = new ArrayList<CategoryShow>(childCount);
			for (int i = 0; i < childCount; i++) {
				DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) rootNode.getChildAt(i);
				mainCategoriesShow.add(new CategoryShow((Category) currentNode.getUserObject(), rootCategory));
			}
			
			List<BookItemInOrder> cart = new ArrayList<BookItemInOrder>();
			
			HttpSession session = event.getSession();
			session.setAttribute(Constants.SESSION_ROOT_CATEGORY, rootNode);
			session.setAttribute(Constants.SESSION_ALL_CATEGORIES, categoriesMap);
			session.setAttribute(Constants.SESSION_MAIN_CATEGORIES, mainCategoriesShow);
			session.setAttribute(Constants.SESSION_CART, cart);
		} catch (SQLException e) {
			//do nothing
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
	}

}
